package com.lovo.interceptor;

import com.lovo.po.Permission;
import com.lovo.po.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class LoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,Object handler) throws IOException {
        System.out.println("=====LoginInterceptor.preHandle=====");

        String requestURI = request.getRequestURI();
        System.out.println("_+____+____+_requestURI = " + requestURI);
        boolean isRight =false;
        if(requestURI.indexOf("login")!=-1){
            return true;
        }else{
            HttpSession session = request.getSession();
            Object obj = session.getAttribute("user");
            if(obj!=null){
                User user =(User)obj;
                List<Permission> permissionList = user.getPermissionList();
                for (Permission p:permissionList) {
                    for (Permission pc:p.getChildren()) {
                        if(pc.getPermissionUrl().equalsIgnoreCase(requestURI)){
                            isRight =true;
                        }
                    }
                    if(isRight){
                        break;
                    }

                }

                if(isRight){
                    return true;
                }else{
                    session.removeAttribute("user");
                    response.sendRedirect("/crm/login.jsp");
                }
            }
            else {
                session.removeAttribute("user");
                response.sendRedirect("/crm/login.jsp");
            }
            return true;
        }
    }

}
